package com.back.controller;

import com.back.common.utils.Result;
import com.back.entity.FavoriteJob;
import com.back.service.IFavoriteJobService;
import com.back.vo.JobListVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 收藏职位前端控制器
 * </p>
 *
 * @author liyang
 * @since 2025-04-26
 */
@RestController
@RequestMapping("/api/user")
public class FavoriteJobController {

    @Autowired
    private IFavoriteJobService favoriteJobService;

    /**
     * 获取收藏的职位列表
     */
    @GetMapping("/favorite-jobs")
    @PreAuthorize("hasAuthority('job_seeker')")
    public Result getFavoriteJobs(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            HttpServletRequest request) {
        
        // 从JWT中获取当前用户信息
        Long userId = 2L; // 示例，实际应从token中获取
        
        // 查询用户收藏的职位
        IPage<JobListVO> jobPage = favoriteJobService.getUserFavorites(userId, page, pageSize);
        
        // 返回结果
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("total", jobPage.getTotal());
        resultMap.put("list", jobPage.getRecords());
        resultMap.put("page", jobPage.getCurrent());
        resultMap.put("pageSize", jobPage.getSize());
        
        return Result.ok().data(resultMap);
    }
    
    /**
     * 收藏职位
     */
    @PostMapping("/favorite-jobs")
    @PreAuthorize("hasAuthority('job_seeker')")
    public Result addFavoriteJob(@RequestBody Map<String, Long> params, HttpServletRequest request) {
        // 从JWT中获取当前用户信息
        Long userId = 2L; // 示例，实际应从token中获取
        
        // 获取职位ID
        Long jobId = params.get("jobId");
        if (jobId == null) {
            return Result.error().message("职位ID不能为空");
        }
        
        try {
            // 收藏职位
            FavoriteJob favoriteJob = favoriteJobService.addFavorite(jobId, userId);
            
            Map<String, Object> data = new HashMap<>();
            data.put("id", favoriteJob.getId());
            data.put("userId", favoriteJob.getUserId());
            data.put("jobId", favoriteJob.getJobId());
            data.put("createTime", favoriteJob.getCreateTime());
            
            return Result.ok().message("收藏成功").data(data);
        } catch (Exception e) {
            return Result.error().message("收藏失败：" + e.getMessage());
        }
    }
    
    /**
     * 取消收藏职位
     */
    @DeleteMapping("/favorite-jobs/{jobId}")
    @PreAuthorize("hasAuthority('job_seeker')")
    public Result removeFavoriteJob(@PathVariable Long jobId, HttpServletRequest request) {
        // 从JWT中获取当前用户信息
        Long userId = 2L; // 示例，实际应从token中获取
        
        boolean result = favoriteJobService.removeFavorite(jobId, userId);
        if (result) {
            return Result.ok().message("已取消收藏");
        } else {
            return Result.error().message("取消收藏失败");
        }
    }
    
    /**
     * 判断职位是否已收藏
     */
    @GetMapping("/favorite-jobs/check/{jobId}")
    @PreAuthorize("hasAuthority('job_seeker')")
    public Result checkFavoriteJob(@PathVariable Long jobId, HttpServletRequest request) {
        // 从JWT中获取当前用户信息
        Long userId = 2L; // 示例，实际应从token中获取
        
        boolean isFavorite = favoriteJobService.checkFavorite(jobId, userId);
        
        Map<String, Object> data = new HashMap<>();
        data.put("jobId", jobId);
        data.put("isFavorite", isFavorite);
        
        return Result.ok().data(data);
    }
}
